package com.cms.controller.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cms.common.kit.ResponseKit;
import com.cms.common.kit.StrKit;
import com.cms.common.kit.Tree;
import com.cms.common.kit.TreeBuilder;
import com.cms.common.util.pass.JsonUtil;
import com.cms.controller.BaseController;
import com.cms.model.Res;
import com.cms.plugin.db.Page;
import com.cms.validate.Rule;
import com.cms.validate.ValidForm;


@Controller
@RequestMapping(value = "/admin/resource")
public class ResourceController extends BaseController{

	private static final String LIST_PAGE="admin/resource/res_list";
	private static final String ADD_PAGE="admin/resource/res_add";
	
	@RequestMapping(value = "/index")
	public String index(Map<String, Object> map,String page,HttpServletRequest request) {
		Page<Res> paginate = Res.dao.paginate(toInt(page, 1), 100);
		List<Tree> buildListToTree = TreeBuilder.buildResToTree(paginate.getList());
		map.put("list",buildListToTree );
		map.put("page", paginate);
		return LIST_PAGE;
	}
	
	@RequestMapping(value = "/toAdd")
	public String toAdd(Map<String, Object> map,String id,HttpServletRequest request) {
		Res w = Res.dao.findById(id);
		map.put("bean", w);
		Page<Res> paginate = Res.dao.paginate(toInt("1", 1), 100);
		List<Tree> buildListToTree = TreeBuilder.buildResToTree(paginate.getList());
		map.put("res_tree",JsonUtil.toJson(buildListToTree) );
		return ADD_PAGE;
	}
	
	@RequestMapping(value = "/delete")
	public @ResponseBody String delete(Map<String, Object> map,String ids,HttpServletRequest request) {
		return Res.dao.deleteByIds(ids)==true?ResponseKit.responseSuccess("操作成功!"):ResponseKit.responseError("操作失败！");
	}
	@RequestMapping(value = "/add")
	public @ResponseBody String add(Map<String, Object> map,String id,HttpServletRequest request) {
		List<Rule> rules=new ArrayList<>();
		rules.add(new Rule().setField("text").setLabel("标题").setRules("required"));
		String errorMsg = ValidForm.validform(request, rules);
		if(!StrKit.isBlank(errorMsg)){
			return ResponseKit.responseError(errorMsg);
		}
		boolean success=false;
		if(StrKit.isBlank(id)){
			success=getModel(Res.class).save();
		}else{
			success=getModel(Res.class).update();
		}
		return success==true?ResponseKit.responseSuccess("操作成功!"):ResponseKit.responseError("操作失败！");
	}
	
}
